import {action, observable, runInAction} from "mobx";
import {BaseResInterface, BaseResInterfaceWithData, sendGetRequest} from "../../../net";
import {ProductModelInterface} from "../../../net/instance/CommenModelInstance";
import {realm} from "../../../dao";
import {BoutiquesStore} from "./boutiques";


interface ProductList {
    count: number,
    rows: ProductModelInterface[]
}

export class ProductListStore {
    @observable
    products: ProductModelInterface[] = [];
    @observable
    count: number = 0;

    @action.bound
    async getProducts(pageNum: number, pageSize: number) {
        const {data} = await sendGetRequest<BaseResInterfaceWithData<ProductList>>("main/getProductsByPage", {
            pageNum,
            pageSize
        });
        runInAction(() => {
            [].push.apply(this.products, data.rows);
            this.count = data.count;
        });

    }

    @action.bound
    async refreshProducts(pageNum: number, pageSize: number) {
        const {data} = await sendGetRequest<BaseResInterfaceWithData<ProductList>>("main/getProductsByPage", {
            pageNum,
            pageSize
        });
        runInAction(() => {
            this.products = data.rows;
            this.count = data.count;
        });
        realm.write(() => {
            data.rows.forEach((product) => {
                realm.create<ProductModelInterface>("Product", product, true);
            })
        });
    }


}
export function getProductListStoreInstance() {
    return new ProductListStore();
}

const ProductListStoreInstance = getProductListStoreInstance();
export default ProductListStoreInstance